package com.qqtech.qquan.mall.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.BizzLevel2Enum;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.ad.enums.AdTypeDictEnum;
import com.qqtech.qquan.ad.model.AdBaseVo;
import com.qqtech.qquan.ad.service.AdBaseService;
import com.qqtech.qquan.circle.model.CircleBaseVo;
import com.qqtech.qquan.circle.service.CircleBaseService;
import com.qqtech.qquan.mall.enums.MallBrandStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallCategoryStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallConst;
import com.qqtech.qquan.mall.enums.MallProductSpecStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallProductStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallShopAuditStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallShopStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallShopStyleDictEnum;
import com.qqtech.qquan.mall.enums.MallShopTypeDictEnum;
import com.qqtech.qquan.mall.enums.MallSubjectStatusDictEnum;
import com.qqtech.qquan.mall.enums.MallSupplierTypeDictEnum;
import com.qqtech.qquan.mall.model.MallCategoryQuery;
import com.qqtech.qquan.mall.model.MallCategoryVo;
import com.qqtech.qquan.mall.model.MallProduct;
import com.qqtech.qquan.mall.model.MallProductQuery;
import com.qqtech.qquan.mall.model.MallProductSpecVo;
import com.qqtech.qquan.mall.model.MallProductVo;
import com.qqtech.qquan.mall.model.MallShop;
import com.qqtech.qquan.mall.model.MallShopQuery;
import com.qqtech.qquan.mall.model.MallShopVo;
import com.qqtech.qquan.mall.model.MallSubjectQuery;
import com.qqtech.qquan.mall.model.MallSubjectVo;
import com.qqtech.qquan.mall.model.MallSupplier;
import com.qqtech.qquan.mall.model.MallSupplierQuery;
import com.qqtech.qquan.mall.model.MallSupplierVo;
import com.qqtech.qquan.mall.service.MallBrandService;
import com.qqtech.qquan.mall.service.MallCartService;
import com.qqtech.qquan.mall.service.MallCategoryService;
import com.qqtech.qquan.mall.service.MallProductService;
import com.qqtech.qquan.mall.service.MallProductSpecService;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.mall.service.MallSubjectService;
import com.qqtech.qquan.mall.service.MallSupplierService;
import com.qqtech.qquan.mall.service.MallSysDictService;
import com.qqtech.qquan.pub.model.PubConcern;
import com.qqtech.qquan.pub.service.PubConcernService;
import com.qqtech.qquan.pub.service.PubFeedbackService;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.model.UserLoginVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/mall/product")
public class MallProductController extends BaseWebController<MallProduct, MallProductQuery> {
	@Resource
	private MallProductService mallProductService;
	@Resource
	private MallCartService mallCartService;
	@Resource
	private MallShopService mallShopService;
	@Resource
	private PubConcernService pubConcernService;
	@Resource
	private CircleBaseService circleBaseService;
	@Resource
	private PubFeedbackService pubFeedbackService;
	@Resource
	private MallSupplierService mallSupplierService;
	@Resource
	private MallProductSpecService mallProductSpecService;
	@Resource
	private MallCategoryService mallCategoryService;
	@Resource
	private MallSubjectService mallSubjectService;
	@Resource
	private MallBrandService mallBrandService;
	@Resource
	private MallSysDictService mallSysDictService;

	@Resource
	private AdBaseService adBaseService;
	@Resource
	private UserBaseService userBaseService;

	@Override
	protected BaseService<MallProduct> getBaseService() {
		return mallProductService;
	}

	/**
	 * 商城首页
	 * 
	 * @param mallProductQuery
	 * @return
	 */
	@RequestMapping(value = "/index")
	@ResponseBody
	public Result index(@RequestBody MallProductQuery mallProductQuery) {
		Result result = new Result();
		MallShopQuery mallShopQuery = new MallShopQuery();
		mallShopQuery.setType(MallShopTypeDictEnum.SUPERMARKET.getCode());
		// 直营商城
		MallShop shop = mallShopService.getOne(mallShopQuery);
		if (shop == null) {
			result.addErr("无法找到店铺信息");
			return result;
		}

		mallProductQuery.setShopId(shop.getId());

		// result = searchProduct(mallProductQuery);
		// 广告轮播\分类\商品分类栏目\便利店 信息
		result = getProductMap(mallProductQuery);

		// 社区供应商栏目 TODO
		/*
		 * Pageable pageKitLocal = new PageKit(1, 3,new PageOrder(Direction.ASC,
		 * "oidx")); MallSupplierQuery localSupplierQuery = new
		 * MallSupplierQuery();
		 * localSupplierQuery.setType(MallSupplierTypeDictEnum.LOCAL.getCode());
		 * localSupplierQuery.setStatus(MallBrandStatusDictEnum.NORMAL.getCode()
		 * ); List<MallSupplierVo> localSpList =
		 * mallSupplierService.queryList(localSupplierQuery, pageKitLocal);
		 * if(localSpList != null && localSpList.size() > 0){
		 * result.put("localSpList", localSpList); }
		 */

		// 圈圈直供品牌
		Pageable pageKitExternal = new PageKit(1, 5, new PageOrder(Direction.ASC, "oidx"));
		MallSupplierQuery supplierQuery = new MallSupplierQuery();
		supplierQuery.setType(MallSupplierTypeDictEnum.EXTERNAL.getCode());
		supplierQuery.setStatus(MallBrandStatusDictEnum.NORMAL.getCode());
		List<MallSupplierVo> externalSpList = mallSupplierService.queryList(supplierQuery, pageKitExternal);
		if (externalSpList != null && externalSpList.size() > 0) {
			result.put("externalSpList", externalSpList);
		}

		// 活动专区
		Pageable pageKitSueject = new PageKit(1, 3, new PageOrder(Direction.ASC, "oidx"));
		MallSubjectQuery subjectQuery = new MallSubjectQuery();
		subjectQuery.setStatus(MallSubjectStatusDictEnum.NORMAL.getCode());
		List<MallSubjectVo> subjectList = mallSubjectService.queryList(subjectQuery, pageKitSueject);
		if (subjectList != null && subjectList.size() > 0) {
			result.put("subjectList", subjectList);
		}

		// 商品推荐模块
		String returnStr = mallProductService.showRecommendModule(MallConst.PARAMKEY_MALL_RECOMMEND_SHOW);
		if (StringUtil.isNotBlank(returnStr) && YesNoEnum.YES.getCode() == Integer.valueOf(returnStr).intValue()) {
			MallProductQuery recommentProductQuery = new MallProductQuery();
			recommentProductQuery.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());
			recommentProductQuery.setIsRecommend(YesNoEnum.YES.getCode());
			recommentProductQuery.setShopId(shop.getId());
			Pageable pageable = new PageKit(mallProductQuery.getPage(), new PageOrder(Direction.ASC, "recommendOidx"));
			Page<MallProductVo> recommendPage = mallProductService.queryPageList(recommentProductQuery, pageable);
			result.put("showRecommend", true);
			result.put("recommendPage", recommendPage);
		} else {
			result.put("showRecommend", false);
		}

		// 购物车总数
		if (super.getUserId() != null && shop.getId() != null) {
			int cartTotalProduct = mallCartService.getTotalQuantity(super.getUserId(), shop.getId());
			result.put("cartTotalProduct", cartTotalProduct);
		}

		return result;
	}

	/**
	 * 商品搜索(封装，前台页面每行显示两个)
	 * 
	 * @param mallProductQuery
	 * @return
	 */
	@RequestMapping(value = "/searchProduct")
	@ResponseBody
	public Result searchProduct(@RequestBody MallProductQuery mallProductQuery) {
		Result result = new Result();
		String oidx = "DESC-newAt";
		if (StringUtil.isNotBlank(mallProductQuery.getOidx()) && mallProductQuery.getOidx().indexOf("-") > -1) {
			oidx = mallProductQuery.getOidx();
		}
		String[] oidxArr = oidx.split("-");
		Direction direction = Direction.valueOf(oidxArr[0]);
		// 商品列表
		mallProductQuery.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());
		Pageable pageKit = new PageKit(mallProductQuery.getPage(), 30, new PageOrder(direction, oidxArr[1]));
		Page<MallProductVo> page = mallProductService.queryPageList(mallProductQuery, pageKit);
		List<MallProductVo> list = page.getContent();
		if (list != null && list.size() > 0) {
			LinkedHashMap<String, List<MallProductVo>> productMap = new LinkedHashMap<String, List<MallProductVo>>();
			int startIndex = 0;
			if (mallProductQuery.getPage() != null && mallProductQuery.getPage() > 1) {
				startIndex = (mallProductQuery.getPage() - 1) * 30;
			}
			for (int i = 0; i < list.size(); i++) {
				MallProductVo mallProductVo = new MallProductVo();
				mallProductVo = list.get(i);
				mallProductVo.setImgString(mallProductVo.getImg(), MallConst.IMG_SMALL);
				if (mallProductVo.isHasImg()) {
					mallProductVo.setImg(mallProductVo.getImgItems().get(0).getSource());
				}

				// 封装
				int key = startIndex / 2 + 1;
				String keyStr = key + "";
				if (productMap.containsKey(keyStr)) {
					List<MallProductVo> productList = productMap.get(keyStr);
					productList.add(mallProductVo);
				} else {
					List<MallProductVo> newproductList = new ArrayList<MallProductVo>();
					newproductList.add(mallProductVo);
					productMap.put(keyStr, newproductList);
				}
				startIndex++;
			}
			result.put("productMap", productMap);
			result.put("totalPages", page.getTotalPages());
			result.put("contentSize", page.getContent().size());
		}
		return result;

	}

	/**
	 * 详情
	 * 
	 * @param mallProductQuery
	 * @return
	 */
	@RequestMapping(value = "/detail")
	@ResponseBody
	public Result detail(@RequestBody MallProductQuery mallProductQuery) {
		Result result = new Result();
		Integer productId = mallProductQuery.getId();
		if (productId == null || productId == 0) {
			result.addErr("商品id为空！");
			return result;
		}
		MallShopVo mallShop = new MallShopVo();
		MallProductVo mallProduct = mallProductService.getById(productId);
		if (mallProduct == null) {
			result.addErr("找不到该商品！");
			return result;
		} else if (mallProduct.getStatus() != MallProductStatusDictEnum.ONSHELF.getCode()) {
			result.addErr("该商品已删除或下架！");
			return result;
		} else {
			mallProductService.increasePv(productId);// 点击量
			// 商品规格
			List<MallProductSpecVo> productSpecLst = mallProductSpecService.queryListByProductId(mallProduct.getId());
			// 价格升序排序
			Comparator<MallProductSpecVo> comparator = new Comparator<MallProductSpecVo>() {
				@Override
				public int compare(MallProductSpecVo ps1, MallProductSpecVo ps2) {
					return ps1.getPrice().compareTo(ps2.getPrice());// 升序
				}
			};
			List<MallProductSpecVo> tmpList = Lists.newArrayList(productSpecLst);
			Collections.sort(tmpList, comparator);
			mallProduct.setProductSpecLst(tmpList);
			mallProduct.setImgString(mallProduct.getImg(), MallConst.IMG_BIG);

			mallShop = mallShopService.getById(mallProduct.getShopId());
			if (mallShop != null) {
				if (mallShop.getType().intValue() == MallShopTypeDictEnum.SUPERMARKET.getCode()) {
					MallSupplier supplier = mallSupplierService.getById(mallProduct.getSupplierId());
					if (supplier != null) {
						mallProduct.setSupplierTypeCode(supplier.getType());
						mallProduct.setSupplierTypeStr(MallSupplierTypeDictEnum.getDesc(supplier.getType()));
					}
				} else if (mallShop.getType().intValue() == MallShopTypeDictEnum.QQMALLSHOP.getCode()) {
					UserBaseVo creator = userBaseService.getById(mallShop.getCreatorId());
					if (creator != null) {
						mallShop.setUserNick(creator.getNick());
					}
					mallProduct.setMallShopVo(mallShop);
				}
				mallProduct.setShopType(mallShop.getType());
			}
			result.put("mallProduct", mallProduct);
		}
		Integer curUserId = super.getUserId();
		if (null != curUserId) {
			// 是否被关注
			addConcernInfo(mallProduct);
			// 购物车总数
			int cartTotalProduct = mallCartService.getTotalQuantity(curUserId, mallProduct.getShopId());
			result.put("cartTotalProduct", cartTotalProduct);
			// 购物车商品价格合计
			// BigDecimal cartTotalPrice =
			// mallCartService.getTotalPrice(super.getUserId(),
			// mallProduct.getShopId());
			// result.put("cartTotalPrice", cartTotalPrice);

			List<CircleBaseVo> myCreateCircles = circleBaseService.queryMyCreatedCircles(curUserId);
			result.put("myCreateCircles", myCreateCircles);
		}
		// 商品评价数量
		int feedbackCount = 0;
		if (mallShop.getType() != null) {
			if (mallShop.getType().intValue() == MallShopTypeDictEnum.QQMALLSHOP.getCode()) {
				feedbackCount = pubFeedbackService.feedbackCount(mallProduct.getId(), "", null, null, 6, 1);
			} else if (mallShop.getType().intValue() == MallShopTypeDictEnum.SUPERMARKET.getCode()) {
				feedbackCount = pubFeedbackService.feedbackCount(mallProduct.getId(), "", null, null, 2, 1);
			}
		}
		result.put("feedbackCount", feedbackCount);
		return result;
	}

	private void addConcernInfo(MallProductVo productVo) {
		PubConcern pubConcern = new PubConcern();
		UserLoginVo user = super.getLoginUser();
		pubConcern.setCreatorId(user.getId());
		pubConcern.setBizzId(productVo.getId());
		pubConcern.setBizzType(BizzLevel2Enum.MALL_PRODUCT.getCode());
		PubConcern pc = pubConcernService.getOne(pubConcern);
		if (pc == null) {
			productVo.setIsConcern(YesNoEnum.NO.getCode());
		} else {
			productVo.setIsConcern(YesNoEnum.YES.getCode());
		}
	}

	/**
	 * 获取商品图文详情
	 * 
	 * @param mallProductQuery
	 * @return
	 */
	@RequestMapping(value = "/getProductResume")
	@ResponseBody
	public Result getProductResume(@RequestBody MallProductQuery mallProductQuery) {
		Result result = new Result();
		Integer productId = mallProductQuery.getId();
		if (productId == null || productId == 0) {
			result.addErr("商品id为空！");
			return result;
		}
		MallProductVo mallProduct = mallProductService.getById(productId);
		if (mallProduct == null) {
			result.addErr("找不到该商品！");
			return result;
		} else if (mallProduct.getStatus() != MallProductStatusDictEnum.ONSHELF.getCode()) {
			result.addErr("该商品已删除或下架！");
			return result;
		} else {
			mallProduct.setImgString(mallProduct.getResumeImg(), MallConst.IMG_RESUME);
			result.put("imgItems", mallProduct.getImgItems());
			result.put("resumeText", mallProduct.getResume());
		}

		return result;
	}

	/**
	 * 获取圈圈便利店
	 * 
	 * @param communityId
	 * @return
	 */
	@RequestMapping(value = "/getQqStore")
	@ResponseBody
	public Result getQqStore(@RequestBody Map<String, String> map) {
		Result result = new Result();
		String communityId = map.get("communityId");
		int iCommunityId = 0;
		if (StringUtil.isNotBlank(communityId)) {
			iCommunityId = new Integer(communityId);
		}
		// 便利店信息
		MallShopQuery qqStoreQuery = new MallShopQuery();
		qqStoreQuery.setCommunityId(iCommunityId);
		qqStoreQuery.setStyle(MallShopStyleDictEnum.QQSTORE.getCode());
		qqStoreQuery.setStatus(MallShopStatusDictEnum.NORMAL.getCode());
		qqStoreQuery.setAuditStatus(MallShopAuditStatusDictEnum.NORMAL.getCode());
		List<MallShopVo> qqStoreList = mallShopService.queryList(qqStoreQuery);
		String existQqStore = "" + YesNoEnum.NO.getCode();
		if (qqStoreList != null && qqStoreList.size() > 0) {
			MallShopVo qqStore = qqStoreList.get(0);
			result.put("qqStore", qqStore);
			existQqStore = "" + YesNoEnum.YES.getCode();
			MallProductQuery mpq = new MallProductQuery();
			mpq.setShopId(qqStore.getId());
			mpq.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());
			Pageable pageKit = new PageKit(1, 3, new PageOrder(Direction.DESC, "newAt"));
			Page<MallProductVo> page = mallProductService.queryPageList(mpq, pageKit);
			if (page != null) {
				for (MallProductVo mallProductVo : page) {
					mallProductVo.setImgString(mallProductVo.getImg(), MallConst.IMG_SMALL);
					if (mallProductVo.isHasImg()) {
						mallProductVo.setImg(mallProductVo.getImgItems().get(0).getSource());
					}
				}
				result.put("qqStoreProducts", page.getContent());
			}
		}
		result.put("existQqStore", existQqStore);
		return result;
	}

	/**
	 * 获取首页货架数据
	 * 
	 * @param mallProductQuery
	 * @return
	 */
	@RequestMapping(value = "/getProductMap")
	@ResponseBody
	public Result getProductMap(@RequestBody MallProductQuery mallProductQuery) {
		Result result = new Result();

		result = getBannerList(result, mallProductQuery.getCommunityId());
		// 便利店信息
		MallShopQuery qqStoreQuery = new MallShopQuery();
		qqStoreQuery.setCommunityId(mallProductQuery.getCommunityId());
		qqStoreQuery.setStyle(MallShopStyleDictEnum.QQSTORE.getCode());
		qqStoreQuery.setStatus(MallShopStatusDictEnum.NORMAL.getCode());
		qqStoreQuery.setAuditStatus(MallShopAuditStatusDictEnum.NORMAL.getCode());
		List<MallShopVo> qqStoreList = mallShopService.queryList(qqStoreQuery);
		String existQqStore = "" + YesNoEnum.NO.getCode();
		if (qqStoreList != null && qqStoreList.size() > 0) {
			MallShopVo qqStore = qqStoreList.get(0);
			result.put("qqStore", qqStore);
			existQqStore = "" + YesNoEnum.YES.getCode();
			MallProductQuery mpq = new MallProductQuery();
			mpq.setShopId(qqStore.getId());
			mpq.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());
			Pageable pageKit = new PageKit(mallProductQuery.getPage(), 3, new PageOrder(Direction.DESC, "newAt"));
			Page<MallProductVo> page = mallProductService.queryPageList(mpq, pageKit);
			if (page != null) {
				for (MallProductVo mallProductVo : page) {
					mallProductVo.setImgString(mallProductVo.getImg(), MallConst.IMG_SMALL);
					if (mallProductVo.isHasImg()) {
						mallProductVo.setImg(mallProductVo.getImgItems().get(0).getSource());
					}
				}
				result.put("qqStoreProducts", page.getContent());
			}
		}
		result.put("existQqStore", existQqStore);
		// 一级分类,9个
		MallCategoryQuery query = new MallCategoryQuery();
		query.setParentId("0");
		query.setStatus(MallCategoryStatusDictEnum.VALID.getCode());
		Pageable p = new PageKit(1, 9, new PageOrder(Direction.ASC, "oidx"));
		List<MallCategoryVo> firstLevelList = mallCategoryService.queryList(query, p);
		result.put("categoryList", firstLevelList);

		// 取货架 取商品
		List<MallCategoryVo> categoryList = mallCategoryService
				.queryFirstLevelList(MallCategoryStatusDictEnum.VALID.getCode());
		if (categoryList != null && categoryList.size() > 0) {
			for (MallCategoryVo categoryVo : categoryList) {
				mallProductQuery.setCategoryId(categoryVo.getCategoryId());
				mallProductQuery.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());
				Pageable pageKit = new PageKit(mallProductQuery.getPage(), 3, new PageOrder(Direction.DESC, "newAt"));
				Page<MallProductVo> page = mallProductService.queryPageList(mallProductQuery, pageKit);
				if (page != null) {
					for (MallProductVo mallProductVo : page) {
						mallProductVo.setImgString(mallProductVo.getImg(), MallConst.IMG_SMALL);
						if (mallProductVo.isHasImg()) {
							mallProductVo.setImg(mallProductVo.getImgItems().get(0).getSource());
						}
					}
					categoryVo.setProductList(page.getContent());
				}

			}
		}
		result.put("list", categoryList);

		return result;
	}

	/**
	 * banner列表
	 * 
	 * @param mallSupplierQuery
	 * @return
	 */
	private Result getBannerList(Result result, Integer communtiyId) {
		List<AdBaseVo> showList = adBaseService.getAdListByType(AdTypeDictEnum.MALL, communtiyId);
		List<Map<String, Object>> bannerList = new ArrayList<Map<String, Object>>();
		if (showList != null && showList.size() > 0) {
			for (AdBaseVo adBase : showList) {
				if (StringUtil.isNotBlank(adBase.getImg())) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("template", "0");
					map.put("imgs", adBase.getImgHandleDomain() + adBase.getImg() + MallConst.IMG_SUPPLIER_BANNER);
					map.put("path", adBase.getPath());
					map.put("jsonData", adBase.getJsonData());
					bannerList.add(map);
				}
			}
			result.put("bannerList", bannerList);
		}
		return result;
	}

	/**
	 * 获取专区商品列表
	 * 
	 * @param mallProductQuery
	 * @return
	 */
	@RequestMapping(value = "/queryPageBySubject")
	@ResponseBody
	public Result queryPageBySubject(@RequestBody MallProductQuery mallProductQuery) {
		Result result = new Result();
		String oidx = "DESC-newAt";
		if (StringUtil.isNotBlank(mallProductQuery.getOidx()) && mallProductQuery.getOidx().indexOf("-") > -1) {
			oidx = mallProductQuery.getOidx();
		}
		String[] oidxArr = oidx.split("-");
		Direction direction = Direction.valueOf(oidxArr[0]);
		Pageable pageKit = new PageKit(mallProductQuery.getPage(), 30, new PageOrder(direction, "mp." + oidxArr[1]));
		Page<MallProductVo> page = mallProductService.queryPageBySubject(mallProductQuery, pageKit);
		List<MallProductVo> list = page.getContent();
		if (list != null && list.size() > 0) {
			LinkedHashMap<String, List<MallProductVo>> productMap = new LinkedHashMap<String, List<MallProductVo>>();
			int startIndex = 0;
			if (mallProductQuery.getPage() != null && mallProductQuery.getPage() > 1) {
				startIndex = (mallProductQuery.getPage() - 1) * 30;
			}
			for (int i = 0; i < list.size(); i++) {
				MallProductVo mallProductVo = new MallProductVo();
				mallProductVo = list.get(i);
				mallProductVo.setImgString(mallProductVo.getImg(), MallConst.IMG_SMALL);
				if (mallProductVo.isHasImg()) {
					mallProductVo.setImg(mallProductVo.getImgItems().get(0).getSource());
				}

				// 封装
				int key = startIndex / 2 + 1;
				String keyStr = key + "";
				if (productMap.containsKey(keyStr)) {
					List<MallProductVo> productList = productMap.get(keyStr);
					productList.add(mallProductVo);
				} else {
					List<MallProductVo> newproductList = new ArrayList<MallProductVo>();
					newproductList.add(mallProductVo);
					productMap.put(keyStr, newproductList);
				}
				startIndex++;
			}
			result.put("productMap", productMap);
			result.put("totalPages", page.getTotalPages());
			result.put("contentSize", page.getContent().size());
		}

		return result;
	}

	/**
	 * 圈商-发布商品
	 * 
	 * @param mallProductVo
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/doAdd")
	@ResponseBody
	public Result doAdd(@RequestBody MallProductVo mallProductVo) {
		Result ret = new Result();
		if (mallProductVo == null) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(mallProductVo.getName())) {
				ret.addErr("产品名称不能为空");
			} else if (mallProductVo.getName().length() > 32) {
				ret.addErr("产品名称不能超过32个字符");
			}
			mallProductVo.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());// 默认上架
			if (mallProductVo.getCategoryId() == null) {
				ret.addErr("分类不能为空");
			}
			// 店铺商品推荐个数不能大于6个
			if (mallProductVo.getShopId() != null && mallProductVo.getShopId().intValue() != 1
					&& mallProductVo.getIsRecommend() != null
					&& mallProductVo.getIsRecommend().intValue() == YesNoEnum.YES.getCode()) {
				int c = mallProductService.getRecommendCount(mallProductVo.getShopId());
				int maxCount = 6;
				if (c >= maxCount) {
					ret.addErr("已推荐了" + c + "个商品，不能超过" + maxCount + "个");
				}
			}
		}
		List<MallProductSpecVo> specLst = mallProductVo.getProductSpecLst();
		if (ret.checkForm()) {
			Timestamp now = TimeUtil.now();
			MallProduct entity = this.initProduct(mallProductVo);
			entity.setCategoryId(mallProductVo.getCategoryId());
			entity.setPv(0);
			entity.setSaleCount(0);
			entity.setFeedbackCount(0);
			entity.setStatusAt(now);
			entity.setNewAt(now);
			entity.setUpdAt(now);
			// 规格信息
			if (specLst != null && specLst.size() > 0) {
				Integer totalStock = 0;
				BigDecimal minPrice = BigDecimal.ZERO;
				BigDecimal currentPrice = BigDecimal.ZERO;
				for (int i = 0; i < specLst.size(); i++) {
					MallProductSpecVo specVo = specLst.get(i);
					currentPrice = specVo.getPrice();
					if (currentPrice == null) {
						ret.addErr("商品规格价格为空");
						return ret;
					}
					if (i > 0) {
						if (minPrice.compareTo(currentPrice) == 1) {// 设置商品最低价格
							minPrice = currentPrice;
						}
					} else {
						minPrice = currentPrice;
					}

					specVo.setColor("");
					totalStock += specVo.getStock();
				}
				entity.setPrice(minPrice);
				entity.setMarketPrice(specLst.get(0).getMarketPrice());
				entity.setStock(totalStock);
				mallProductService.handleSaveProduct(entity, specLst);
			}
		}
		return ret;
	}

	// 圈商-发布商品-初始化一个规格【因为没有传规格进来】
	private MallProductSpecVo initOneMallProductSpec(MallProduct product) {
		MallProductSpecVo mallProductSpec = new MallProductSpecVo();
		mallProductSpec.setColor("");
		mallProductSpec.setStock(product.getStock());
		mallProductSpec.setPrice(product.getPrice());
		mallProductSpec.setMarketPrice(product.getMarketPrice());
		mallProductSpec.setStatus(MallProductSpecStatusDictEnum.NORMAL.getCode());// 正常
		mallProductSpec.setSpecName(product.getName());
		return mallProductSpec;
	}

	/**
	 * 圈商-更新商品
	 * 
	 * @param mallProductVo
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/doUpdate")
	@ResponseBody
	public Result doUpdate(@RequestBody MallProductVo product) {
		Result ret = new Result();
		MallProduct oldProduct = null;
		Integer productId = product.getId();
		if (product == null || productId == null) {
			ret.addErr("参数不能为空");
		} else {
			oldProduct = mallProductService.getById(product.getId());
			if (oldProduct == null) {
				ret.addErr("不存在该产品");
			} else {
				// 店铺商品推荐个数不能大于6个
				if (oldProduct.getShopId() != null && oldProduct.getShopId().intValue() != 1
						&& oldProduct.getIsRecommend().intValue() == YesNoEnum.NO.getCode()
						&& product.getIsRecommend() != null
						&& product.getIsRecommend().intValue() == YesNoEnum.YES.getCode()) {
					int c = mallProductService.getRecommendCount(oldProduct.getShopId());
					int maxCount = 6;
					if (c >= maxCount) {
						ret.addErr("已推荐了" + c + "个商品，不能超过" + maxCount + "个");
					}
				}
			}
		}
		if (ret.checkForm()) {
			MallProduct product4update = new MallProductVo();
			product4update.setId(product.getId());
			product4update.setName(product.getName().trim());

			product4update.setMarketPrice(product.getMarketPrice());
			product4update.setPrice(product.getPrice());
			product4update.setStock(product.getStock());
			if (product.getCategoryId() != null) {
				product4update.setCategoryId(product.getCategoryId());
			}
			product4update.setUnit(product.getUnit().trim());
			product4update.setIsAllNew(product.getIsAllNew());// 是否全新的
			product4update.setBrandName(product.getBrandName());// 品牌名称
			product4update.setImg(StringUtil.isBlank(product.getImg()) ? "" : product.getImg());
			product4update.setResume(StringUtil.isBlank(product.getResume()) ? "" : product.getResume());
			product4update.setResumeImg(StringUtil.isBlank(product.getResumeImg()) ? "" : product.getResumeImg());
			product4update.setBrandName(StringUtil.isBlank(product.getBrandName()) ? "" : product.getBrandName());// 品牌名称
			product4update.setUpdAt(TimeUtil.now());
			product4update.setIsRecommend(
					product.getIsRecommend() == null ? YesNoEnum.NO.getCode() : product.getIsRecommend());
			if (product4update.getIsRecommend().intValue() == YesNoEnum.NO.getCode()) {
				product4update.setRecommendOidx(0);
			} else if (product4update.getIsRecommend().intValue() == YesNoEnum.YES.getCode()) {
				if (oldProduct.getShopId() != null && oldProduct.getShopId().intValue() != 1) {// 店铺商品
					product4update.setRecommendOidx(1);
				}
			}

			// 规格信息
			List<MallProductSpecVo> specLst = product.getProductSpecLst();
			if (specLst != null && specLst.size() > 0) {
				Integer totalStock = 0;
				BigDecimal minPrice = BigDecimal.ZERO;
				BigDecimal currentPrice = BigDecimal.ZERO;
				for (int i = 0; i < specLst.size(); i++) {
					MallProductSpecVo specVo = specLst.get(i);
					currentPrice = specVo.getPrice();
					if (currentPrice == null) {
						ret.addErr("商品规格价格为空");
						return ret;
					}
					if (i > 0) {
						if (minPrice.compareTo(currentPrice) == 1) {// 设置商品最低价格
							minPrice = currentPrice;
						}
					} else {
						minPrice = currentPrice;
					}

					specVo.setColor("");
					totalStock += specVo.getStock();
				}
				product4update.setPrice(minPrice);
				product4update.setMarketPrice(specLst.get(0).getMarketPrice());
				product4update.setStock(totalStock);
				mallProductService.handleUpdateProduct(product4update, specLst);
			}

		}
		return ret;
	}

	@RequestMapping(value = "/queryListByShop")
	@ResponseBody
	public Result queryListByShop(@RequestBody MallProductQuery mallProductQuery) {
		Result ret = new Result();
		String oidx = "DESC-newAt";
		if (StringUtil.isNotBlank(mallProductQuery.getOidx()) && mallProductQuery.getOidx().indexOf("-") > -1) {
			oidx = mallProductQuery.getOidx();
		}
		String[] oidxArr = oidx.split("-");
		Direction direction = Direction.valueOf(oidxArr[0]);
		// 商品列表
		mallProductQuery.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());
		Pageable pageKit = new PageKit(mallProductQuery.getPage(), 30, new PageOrder(direction, oidxArr[1]));
		Page<MallProductVo> page = mallProductService.queryPageList(mallProductQuery, pageKit);
		List<MallProductVo> list = page.getContent();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				MallProductVo mallProductVo = new MallProductVo();
				mallProductVo = list.get(i);
				mallProductVo.setImgString(mallProductVo.getImg(), MallConst.IMG_SMALL);
				if (mallProductVo.isHasImg()) {
					mallProductVo.setImg(mallProductVo.getImgItems().get(0).getSource());
				}

			}
		}
		ret.put("page", page);
		return ret;
	}

	private MallProductVo initProduct(MallProductVo mallProductVo) {
		MallProductVo entity = new MallProductVo();
		entity.setId(mallProductVo.getId());
		entity.setFeature("");
		entity.setName(mallProductVo.getName().trim());
		entity.setSubtitle(mallProductVo.getSubtitle());
		entity.setIsRecommend(mallProductVo.getIsRecommend());
		entity.setMarketPrice(mallProductVo.getMarketPrice());
		entity.setPrice(mallProductVo.getPrice());
		entity.setShopId(mallProductVo.getShopId());
		entity.setStatus(mallProductVo.getStatus());
		entity.setStock(mallProductVo.getStock());
		entity.setUnit(mallProductVo.getUnit().trim());
		entity.setIsAllNew(mallProductVo.getIsAllNew());// 是否全新的
		entity.setBrandName(mallProductVo.getBrandName());// 品牌名称
		entity.setDiscoverRecommend(YesNoEnum.NO.getCode());
		if (mallProductVo.getBrandId() == null) {
			entity.setBrandId(0);
		} else {
			entity.setBrandId(mallProductVo.getBrandId());
		}
		if (mallProductVo.getIsRecommend() == null) {
			mallProductVo.setIsRecommend(YesNoEnum.NO.getCode());
			entity.setIsRecommend(YesNoEnum.NO.getCode());
		}
		if (mallProductVo.getIsRecommend().intValue() == YesNoEnum.NO.getCode()) {// 2不推荐
			entity.setRecommendOidx(0);
		} else {
			entity.setRecommendOidx(mallProductVo.getRecommendOidx() == null ? 1 : mallProductVo.getRecommendOidx());
		}
		if (mallProductVo.getSupplierId() == null) {
			entity.setSupplierId(0);
		} else {
			entity.setSupplierId(mallProductVo.getSupplierId());
		}
		if (StringUtil.isBlank(mallProductVo.getImg())) {
			entity.setImg("");
		} else {
			entity.setImg(mallProductVo.getImg());
		}
		if (mallProductVo.getResume() == null) {
			entity.setResume("");
		} else {
			entity.setResume(mallProductVo.getResume());
		}
		if (StringUtil.isBlank(mallProductVo.getResumeImg())) {
			entity.setResumeImg("");
		} else {
			entity.setResumeImg(mallProductVo.getResumeImg());
		}
		if (mallProductVo.getIsAllNew() == null) {
			entity.setIsAllNew(YesNoEnum.YES.getCode());// 默认是全新
		}
		if (StringUtil.isBlank(mallProductVo.getBrandName())) {
			entity.setBrandName("");// 品牌名称
		}
		return entity;
	}

	/**
	 * 我的店铺--查询上架的商品-分页
	 * 
	 * @param mallProductQuery
	 * @return
	 */
	@RequestMapping(value = "/listOnShelfProducts4MyShop")
	@ResponseBody
	public Result listOnShelfProducts4MyShop(@RequestBody MallProductQuery mallProductQuery) {
		Result ret = new Result();
		Integer shopId = mallProductQuery.getShopId();
		if (shopId == null) {
			ret.addErr("店铺id为空");
			return ret;
		}
		String oidx = "DESC-newAt";
		if (StringUtil.isNotBlank(mallProductQuery.getOidx()) && mallProductQuery.getOidx().indexOf("-") > -1) {
			oidx = mallProductQuery.getOidx();
		}
		String[] oidxArr = oidx.split("-");
		Direction direction = Direction.valueOf(oidxArr[0]);
		mallProductQuery.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());// 上架的
		Pageable pageKit = new PageKit(mallProductQuery.getPage(), new PageOrder(direction, oidxArr[1]));
		Page<MallProductVo> page = mallProductService.queryPageList(mallProductQuery, pageKit);
		List<MallProductVo> productList = page.getContent();
		if (productList != null && productList.size() > 0) {
			for (MallProductVo product : productList) {
				product.setImgString(product.getImg(), MallConst.IMG_SMALL);// 处理小图
				product.setStatusCn("已上架");
			}
		}
		ret.put("productPage", page);
		return ret;
	}

	/**
	 * 我的店铺--查询上架的商品-分页
	 * 
	 * @param mallProductQuery
	 * @return
	 */
	@RequestMapping(value = "/listOffShelfProducts4MyShop")
	@ResponseBody
	public Result listOffShelfProducts4MyShop(@RequestBody MallProductQuery mallProductQuery) {
		Result ret = new Result();
		Integer shopId = mallProductQuery.getShopId();
		if (shopId == null) {
			ret.addErr("店铺id为空");
			return ret;
		}
		String oidx = "DESC-newAt";
		if (StringUtil.isNotBlank(mallProductQuery.getOidx()) && mallProductQuery.getOidx().indexOf("-") > -1) {
			oidx = mallProductQuery.getOidx();
		}
		String[] oidxArr = oidx.split("-");
		Direction direction = Direction.valueOf(oidxArr[0]);
		mallProductQuery.setStatus(MallProductStatusDictEnum.OFFSHELF.getCode());// 上架的
		Pageable pageKit = new PageKit(mallProductQuery.getPage(), new PageOrder(direction, oidxArr[1]));
		Page<MallProductVo> page = mallProductService.queryPageList(mallProductQuery, pageKit);
		List<MallProductVo> productList = page.getContent();
		if (productList != null && productList.size() > 0) {
			for (MallProductVo product : productList) {
				product.setImgString(product.getImg(), MallConst.IMG_SMALL);// 处理小图
				product.setStatusCn("已下架");
			}
		}
		ret.put("productPage", page);
		return ret;
	}

	/**
	 * 下架一个商品
	 * 
	 * @param mallProduct
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/offShelf")
	@ResponseBody
	public Result update(@RequestBody MallProduct mallProduct) {
		Result result = new Result();
		Integer productId = mallProduct.getId();
		if (productId == null) {
			result.addErr("商品id为空");
			return result;
		}
		mallProductService.offShelf(productId);
		return result;
	}

	/**
	 * 上架一个商品
	 * 
	 * @param mallProduct
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/onShelf")
	@ResponseBody
	public Result onShelf(@RequestBody MallProduct mallProduct) {
		Result result = new Result();
		Integer productId = mallProduct.getId();
		if (productId == null) {
			result.addErr("商品id为空");
			return result;
		}
		mallProductService.onShelf(productId);
		return result;
	}

	/**
	 * 加载商品--用于编辑
	 * 
	 * @param mallProductQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/detail4edit")
	@ResponseBody
	public Result detail4edit(@RequestBody MallProductQuery mallProductQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		Integer productId = mallProductQuery.getId();
		if (productId == null || productId == 0) {
			result.addErr("商品id为空！");
			return result;
		}
		MallProductVo mallProduct = mallProductService.getById(productId);
		if (mallProduct == null) {
			result.addErr("找不到该商品！");
			return result;
		}
		// 规格
		List<MallProductSpecVo> productSpecLst = mallProductSpecService.queryListByProductId(mallProduct.getId());
		if (productSpecLst == null) {
			result.addErr("找不到该商品规格！");
			return result;
		}
		mallProduct.setProductSpecLst(productSpecLst);
		Integer shopId = mallProduct.getShopId();// 店铺id
		if (!mallShopService.isShopOwner(curUserId, shopId)) {
			result.addErr("你不是店主,不能操作！");
			return result;
		}
		// 商品类型
		MallCategoryVo mallCategory = mallCategoryService.getByCategoryId(mallProduct.getCategoryId());
		if (mallCategory != null) {
			String CategoryName = mallCategory.getName();
			if (mallCategory.getParentId() != null && !mallCategory.getParentId().equalsIgnoreCase("0")) {
				mallCategory = mallCategoryService.getByCategoryId(mallCategory.getParentId());
				if (mallCategory != null) {
					CategoryName = mallCategory.getName() + "/" + CategoryName;
				}
			}
			mallProduct.setCategoryName(CategoryName);
		}
		result.put("mallProduct", mallProduct);
		return result;
	}

	@RequestMapping(value = "/getProductBySpecId")
	@ResponseBody
	public Result getProductBySpecId(@RequestBody MallProductQuery mallProductQuery) {
		Result ret = new Result();
		if (mallProductQuery.getId() != null) {
			MallProduct mallProduct = mallProductService.getProductBySpecId(mallProductQuery.getId());
			ret.put("mallProduct", mallProduct);
		}
		return ret;
	}

	/**
	 * 店铺（搜索）
	 * 
	 * @param MallProductQuery
	 *            {page:page}
	 * @return
	 */
	@RequestMapping(value = "/search")
	@ResponseBody
	public Result search(@RequestBody MallProductQuery query) {
		Result result = new Result();
		query.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());
		Pageable pageKit = new PageKit(query.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<MallProductVo> page = mallProductService.queryPageList(query, pageKit);
		result.put("page", page);
		return result;
	}
}
